package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;

public class ActionServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		Action action = new PanduanAction();
//		String path = action.exeute(request);
//		RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
//		requestDispatcher.forward(request, response);
		String path = this.getPath(request.getServletPath());
		@SuppressWarnings("unchecked")
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean bean = map.get(path);
		String formName = bean.getForm();
		String type = bean.getType();
		ActionForm actionForm = FullForm.full(formName, request); 
		Action action = null;
		String url = "";
		try {
			Class<?> clazz = Class.forName(type);
			action = (Action)clazz.newInstance();
			url = action.exeute(request, actionForm, bean.getForward());
		}catch(Exception e) {
			e.printStackTrace();
		}
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
		requestDispatcher.forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	private String getPath(String path) {
		return path.split("\\.")[0];
	}
}
